package com.jinzhi.task;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.domain.UserRoleDO;
import com.jinzhi.sys.service.RoleService;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author mengzhichao
 * @create 2022-11-30-9:02
 */
@Component // 把此类托管给 Spring，不能省略
public class TaskUtils {
    @Autowired
    private UserService userService;
    @Autowired
    private UserRoleService userRoleService;


    // 添加定时任务
//    @Scheduled(cron = "0/2 * * * * ?") // cron表达式：两秒执行一次
    @Scheduled(cron = "0 0 0/24 * * ? ") // cron表达式：每天0点触发任务
    public void doTask(){
        System.out.println("开始执行定时任务");
        // 当前时间
        Date now = new Date();
        //找出所有的小程序来源的用户
        List<UserDO> userDOS = userService.selectList(new EntityWrapper<UserDO>().eq("user_source", 1));
        userDOS.forEach(e->{
            // 使用Calendar计算天数差
            Calendar calendarNow = Calendar.getInstance();
            Calendar calendarPast = Calendar.getInstance();
            calendarNow.setTime(now);
            calendarPast.setTime(e.getGmtCreate());
            int diffDays = (int) ((calendarNow.getTimeInMillis() - calendarPast.getTimeInMillis()) / (1000 * 60 * 60 * 24));
            System.out.println("Difference in days: " + diffDays);
            if (diffDays > 30) {
                System.out.println("已经超过30天！删除用户的开通练习角色");
                userRoleService.delete(new EntityWrapper<UserRoleDO>().eq("userId",e.getId()).eq("roleId",1821091094336851970L));
            }
        });
        System.out.println("定时任务执行完毕");

    }








}
